package com.bluewap.api;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bluewap.core.Database;
import com.bluewap.core.StaticVar;
import com.bluewap.core.Util;
import com.bluewap.telco.VivasAdapter;

public class CheckoutServlet extends HttpServlet {
	private static final long serialVersionUID = 8803521997944242216L;
	private Logger log = Logger.getLogger("checkout");
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String transId = req.getParameter("id");
		String token = req.getParameter("token");
		String cpId = req.getParameter("cpid");

		if(!Util.isValidParam(transId) 
				|| !Util.isValidParam(token)
				|| !Util.isValidParam(cpId)){
			log.info(StaticVar.ERROR_PARAM_MISSING + "|" + req.getQueryString());
			Util.printJson(StaticVar.ERROR_PARAM_MISSING, null, resp);
			return;
		}

		//get transaction params from db
		Connection conn = Database.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;

		String contentId = "";
		String contentType = "";
		String price = "";
		String returnUrl = "";
		boolean isExist = false;
		int status = StaticVar.ERROR_ORDERED;
		
		try {
			
			String query = "SELECT * FROM CHECKOUTS" +
			" WHERE ID = ?"  + 
			" AND TOKEN = ?" +
			" AND CP_ID = ?" +
			" AND STATUS = ?" ;
			st = conn.prepareStatement(query);
			st.setInt(1, Integer.valueOf(transId));
			st.setString(2, token);
			st.setInt(3,Integer.valueOf(cpId));
			st.setInt(4, StaticVar.ERROR_ORDERED);
			rs = st.executeQuery();

			while (rs.next()){
				isExist = true;
				contentId = rs.getString(StaticVar.DB_CHECKOUT_CONTENTID);
				contentType = rs.getString(StaticVar.DB_CHECKOUT_CONTENTTYPE);
				price = rs.getString(StaticVar.DB_CHECKOUT_CONTENTPRICE);
				returnUrl = rs.getString(StaticVar.DB_CHECKOUT_RETURNURL);
				status = rs.getInt(StaticVar.DB_CHECKOUT_STATUS);
				break;
			}
		} catch (Exception e) {
			log.error("Error", e);
			Util.printJson(StaticVar.ERROR_INTERNAL_ERROR, null, resp);
			return;
		} finally{
			try {
				if (rs != null) rs.close();
				if (st != null) st.close();
				if (conn != null) Database.closeConnection(conn);
			} catch (Exception e) {
				log.error("Error", e);
			}
		}
		if(!isExist) {
			log.info(StaticVar.ERROR_TRANSACTION_NOT_EXIST + "|" + req.getQueryString());
			returnUrl = Util.buildUrl(returnUrl, transId, token, "", StaticVar.ERROR_TRANSACTION_NOT_EXIST);
			resp.sendRedirect(returnUrl);
			return;
		}
		if(status != StaticVar.ERROR_ORDERED){
			log.info(StaticVar.ERROR_TRANSACTION_EXIST + "|" + req.getQueryString());
			returnUrl = Util.buildUrl(returnUrl, transId, token, "", StaticVar.ERROR_TRANSACTION_EXIST);
			resp.sendRedirect(returnUrl);
			return;			
		}

		//update status to pending
		conn = Database.getConnection();
		try {
		 
			String query = "UPDATE CHECKOUTS" +
			" SET STATUS = ?" + 
			" WHERE ID = ?" ;
			st = conn.prepareStatement(query);
			st.setInt(1,  StaticVar.ERROR_PENDING);
			st.setInt(2, Integer.valueOf(transId));
			st.executeUpdate();
		} catch (Exception e) {
			log.error("Error", e);
			returnUrl = Util.buildUrl(returnUrl, transId, token, "", StaticVar.ERROR_INTERNAL_ERROR);
			resp.sendRedirect(returnUrl);

			return;
		} finally {
			try {
				if (st != null)	st.close();
				if (conn != null) Database.closeConnection(conn);
			} catch (Exception e) {
				log.error("Error", e);
			}
		}

		String vivasToken = VivasAdapter.getToken(transId, price, contentId);
		if(!Util.isValidParam(vivasToken)){
			Util.printJson(StaticVar.ERROR_INTERNAL_ERROR, null, resp);
			return;
		}
		else{
			String redirectlink = VivasAdapter.buildChargeLink(vivasToken, transId, price, contentType, contentId);
			log.info(redirectlink + "|" + req.getQueryString());
			resp.sendRedirect(redirectlink);
			return;
		}
	}
}
